package ui;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JPanel;

import Client.Command;
import Games.GamesController;
import Games.GamesModel;
import ui.Main;

public class GameControllerView extends JPanel implements ActionListener {
	
	private GameFrame gameFrame;
	private JButton subscribeBtn, stopBtn, closeBtn, aiBtn;
	private GamesModel gamesModel;
	
	public GameControllerView(GameFrame gameFrame, GamesModel gamesModel) {
            this.gameFrame = gameFrame;
            this.gamesModel = gamesModel;
            init();
	}
	
	public void init() {
            setLayout(new GridLayout(2,2));
            setBorder(BorderFactory.createTitledBorder("Action: "));
            
            if(Main.ai) {
                aiBtn = new JButton("Turn AI off!");
            } else {
                aiBtn = new JButton("Turn AI on!");
            }
            
            aiBtn.addActionListener(this);
            
            subscribeBtn = new JButton("Subscribe");
            subscribeBtn.addActionListener(this);
            
            stopBtn = new JButton("Forfeit");
            stopBtn.addActionListener(this);
            
            closeBtn = new JButton("Close");
            closeBtn.addActionListener(this);
            
            add(aiBtn);
            add(subscribeBtn);
            add(stopBtn);
            add(closeBtn);
	}

	@Override
	public void actionPerformed(ActionEvent e) {
            if(subscribeBtn == e.getSource()) {
    
                if(gamesModel == null) {
                } else
                    Command.subscribe(gamesModel.getSelectedGame());
                    subscribeBtn.setEnabled(false);
            }
            if(stopBtn == e.getSource()) {
                Command.forfeit();
            }
            if(closeBtn == e.getSource()) {
                Command.forfeit();
                this.gamesModel = null;
                this.gameFrame.dispose();
                this.gameFrame = null;
            }
            if(aiBtn == e.getSource()) {
                if(Main.ai) {
                    aiBtn.setText("Turn AI on!");
                    Main.ai = false;
                } else {
                    aiBtn.setText("Turn AI off!");
                    GamesController.game.chooseMove(GamesController.gamesModel().getPlayersHashMap().get(GamesController.gamesModel().getUs()));
                    GamesController.appendHistory("The AI made a move");
                    Main.ai = true;
                }
            }
	}
}
